package com.hxb.library.widget;


import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import com.hxb.library.base.BaseFragment;

import java.util.List;


public class SYHFragmentAdapter extends FragmentStatePagerAdapter {
    private List<BaseFragment> fragmentList;
    private List<String> titleList;
    private FragmentManager fm;

    public SYHFragmentAdapter(FragmentManager fm, List<BaseFragment> fragmentList) {
        super(fm);
        // TODO Auto-generated constructor stub
        this.fm = fm;
        this.fragmentList = fragmentList;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (titleList != null && titleList.size() > position) {
            return titleList.get(position);
        }
        return super.getPageTitle(position);
    }

    public void setTitleList(List<String> titleList) {
        this.titleList = titleList;
    }

    public void updatePager(List<BaseFragment> fragmentList) {
        this.fragmentList = fragmentList;
        notifyDataSetChanged();
    }

    private int mChildCount = 0;

    @Override
    public void notifyDataSetChanged() {
        // 重写这个方法，取到子Fragment的数量，用于下面的判断，以执行多少次刷新
        mChildCount = getCount();
        super.notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        if (mChildCount > 0) {
            // 这里利用判断执行若干次不缓存，刷新
            mChildCount--;
            // 返回这个是强制ViewPager不缓存，每次滑动都刷新视图
            return POSITION_NONE;
        }
        // 这个则是缓存不刷新视图
        return super.getItemPosition(object);
    }

    @Override
    public Fragment getItem(int arg0) {
        // TODO Auto-generated method stub
        return fragmentList.get(arg0);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return fragmentList == null ? 0 : fragmentList.size();
    }
}
